package com.lzy.system.organization.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzy.exception.BusException;
import com.lzy.system.organization.dto.SysUserMappingAllocationDTO;
import com.lzy.system.organization.dto.convert.SysUserMappingConvert;
import com.lzy.system.organization.entity.*;
import com.lzy.system.organization.mapper.SysDepartmentMapper;
import com.lzy.system.organization.mapper.SysUserBindingMapper;
import com.lzy.system.organization.mapper.SysUserMapper;
import com.lzy.system.organization.service.ISysUserMappingService;
import com.lzy.system.organization.service.ISysUserRoleService;
import com.lzy.system.organization.vo.SysUserMappingVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户映射 服务实现类
 * </p>
 *
 * @author lcc
 * @since 2023-11-25
 */
@Service
public class SysUserMappingServiceImpl extends ServiceImpl<SysUserBindingMapper, SysUserMapping> implements ISysUserMappingService {
    SysUserBindingMapper sysUserBindingMapper;
    SysUserMapper sysUserMapper;
    SysDepartmentMapper sysDepartmentMapper;
    SysUserMappingConvert sysUserMappingConvert;
    ISysUserRoleService iSysUserRoleService;

    @Autowired
    public SysUserMappingServiceImpl(SysUserBindingMapper sysUserBindingMapper, SysUserMapper sysUserMapper, SysDepartmentMapper sysDepartmentMapper, SysUserMappingConvert sysUserMappingConvert,ISysUserRoleService iSysUserRoleService) {
        this.sysUserBindingMapper = sysUserBindingMapper;
        this.sysUserMapper = sysUserMapper;
        this.sysDepartmentMapper = sysDepartmentMapper;
        this.sysUserMappingConvert = sysUserMappingConvert;
        this.iSysUserRoleService = iSysUserRoleService;

    }


    @Override
    public IPage<SysUserMappingVo> getList(String keyword, Long company_id, Long dep_id, long limit, long page) throws BusException {
        IPage list = sysUserBindingMapper.getUserList(new Page(page, limit), keyword, company_id, dep_id);
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(SysUserMapping sysUserMapping) throws BusException {
        return updateById(sysUserMapping);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateDef(Long user_id, Long id, Integer status) throws BusException {
        if (status == 1) {
            update(new UpdateWrapper() {{
                eq("is_def", "1");
                eq("user_id", user_id);
                set("is_def", 0);
            }});
        }
        update(new UpdateWrapper() {{
            eq("id", id);
            set("is_def", status);
        }});
        return true;
    }

    @Override
    public boolean addUser(List<SysUserMappingAllocationDTO> sysUserMappingAllocationDTOS) throws BusException {
        List<SysUserMapping> adds = new ArrayList<>();
        List<SysUserMapping> sysUserMappings = sysUserMappingConvert.toSysUserMappingList(sysUserMappingAllocationDTOS);
        for (SysUserMapping sysUserMapping : sysUserMappings) {
            List<SysUserMapping> list = this.list(new QueryWrapper<SysUserMapping>()
                    .eq("dep_id", sysUserMapping.getDep_id())
                    .eq("user_id", sysUserMapping.getUser_id())
            );
            SysUser sysUser = sysUserMapper.selectById(sysUserMapping.getUser_id());
            SysDepartment sysDepartment = sysDepartmentMapper.selectById(sysUserMapping.getDep_id());
            if (list.size() > 0) {
                throw new BusException(StrUtil.format("{}下已经有{}了", sysDepartment.getDep_name(), sysUser.getNickname()));
            }
            adds.add(
                    new SysUserMapping() {{
                        setIs_def(0);
                        setIs_manage(0);
                        setUser_id(sysUserMapping.getUser_id());
                        setDep_id(sysUserMapping.getDep_id());
                        setCompany_id(sysDepartment.getCompany_id());
                        setOrder_index(0);
                    }}
            );
        }
        this.saveBatch(adds);
        return true;
    }

    @Override
    public boolean delUser(List<SysUserMapping> sysUserMappings) throws BusException {
        List<Long> ids= new ArrayList<>();
        for (SysUserMapping sysUserMapping : sysUserMappings) {
            if(sysUserMapping.getId() == null){
                continue;
            }
            ids.add(sysUserMapping.getId());
        }
        if(ids.size() == 0){
            throw new BusException("至少选一个删除的用户");
        }
        //清空删除用户对于的角色
        for (Long mid : ids) {
            iSysUserRoleService.remove(new QueryWrapper(){{
                eq("mid",mid);
            }});
        }
        return removeBatchByIds(ids);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean savePower(Long mid, List<SysRole> sysRoles) throws BusException {
        SysUserMapping sysUserMapping = getById(mid);
        if(sysUserMapping == null){
            throw new BusException("找不到用户");
        }
        List<SysUserRole> list = new ArrayList<>();
        for (SysRole sysRole : sysRoles) {
            list.add(new SysUserRole(){{
                setRid(sysRole.getId());
                setUid(sysUserMapping.getUser_id());
            }});
        }
        //清空角色
        iSysUserRoleService.remove(new QueryWrapper(){{
            eq("uid",sysUserMapping.getUser_id());
        }});
        return iSysUserRoleService.saveBatch(list);
    }
}
